package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.redis.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private Client client;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;


    @Override
    public void send(String phone) throws Exception {
        //根据手机号获取验证码是否存在
        String key = RedisConstant.APP_LOGIN_PREFIX +phone;
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey){
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //不存在，生成六位随机数验证码
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        //发送验证码
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\""+code+"\"}");
        client.sendSms(smsRequest);
        //保存到redis中，设置过期时间
        redisTemplate.opsForValue().set(key,code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String customLogin(LoginVo loginVo) {
        //校验手机号和验证码是否为空
        String key = loginVo.getPhone();
        String code = loginVo.getCode();
        if (ObjectUtils.isEmpty(key)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (ObjectUtils.isEmpty(code)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //校验验证码是否过期
        String redisCode = redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX +key) +"" ;
        if (ObjectUtils.isEmpty(redisCode)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        //校验验证码是否正确
        if (!redisCode.equals(code)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //检测账号是否存在
        UserInfo userinfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone",loginVo.getPhone()));
        if (ObjectUtils.isEmpty(userinfo)){
            //创建账号
            userinfo = new UserInfo();
            userinfo.setPhone(loginVo.getPhone());
            //设置默认昵称
            userinfo.setNickname("用户"+loginVo.getPhone().substring(loginVo.getPhone().length()-4));
            userinfo.setStatus(BaseStatus.ENABLE);
            userInfoMapper.insert(userinfo);
        }
        //检测账号是否被禁用
        if (userinfo.getStatus() != BaseStatus.ENABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //生成token
        String token = JwtUtil.createToken(1L,loginVo.getPhone());

        return token;
    }
}
